import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:kq_flutter_core_widget/utils/log.dart';

/// 第三方登录调用原生工具类
class ThirdLoginNativeUtil {
  static const _methodChannelName = 'flutter.keqiang.com/thirdLogin';

  static const _platformMethod = MethodChannel(_methodChannelName);

  /// 微信授权登录
  ///
  /// 注意：Android端的FlutterActivity 必须实现[IKqRoute]
  static void wxAuth(
      {Function(WxAuthResultCode resultCode, String? authCode)? callback}) {
    try {
      _platformMethod.invokeMethod('wxAuth').then((value) {
        if (value == null) {
          callback?.call(WxAuthResultCode.failed, null);
          return;
        }
        var code = value['code'];
        if (code == '0') {
          var authCode = value['authCode'];
          callback?.call(WxAuthResultCode.success, authCode);
        } else if (code == '1') {
          callback?.call(WxAuthResultCode.failed, null);
        } else if (code == '-1') {
          callback?.call(WxAuthResultCode.cancel, null);
        } else {
          callback?.call(WxAuthResultCode.notInstall, null);
        }
      });
    } on PlatformException catch (e) {
      debugPrint(e.message);
      callback?.call(WxAuthResultCode.failed, null);
    } catch (e) {
      Log.e(e);
      callback?.call(WxAuthResultCode.failed, null);
    }
  }
}

/// 微信授权结果
enum WxAuthResultCode {
  /// 授权成功
  success,

  /// 授权失败
  failed,

  /// 微信未安装
  notInstall,

  /// 用户取消授权
  cancel
}
